package com.usian.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.jwt.AppJwtUtil;
import com.usian.mapper.WemediaMapper;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;


@Service
public class WmUserServiceImpl extends BaseServiceImpl<WemediaMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmUserDto dto) {

        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword()))return paramError;
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"姓名不存在");
        }
        String psd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
        if (psd.equals(wmUser.getPassword())){
            wmUser.setPassword("");
            wmUser.setSalt("");
            String token = AppJwtUtil.getToken(wmUser.getId().longValue());
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",wmUser);
            return ResponseResult.okResult(map);
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }

    }
}
